﻿#region Declaration

//------------------------------------------------------------------------------
// Compas Information Techonoly Co., Ltd
// The Initial Developer of the Original Code is CompasSolutions.
// All Rights Reserved.
// 
// Contributor(s): _______. 
//------------------------------------------------------------------------------

#endregion

#region Using Directives

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Security.Principal;

#endregion

namespace QuickDev.Common.HttpModules
{
    /// <summary>
    /// Authenticate user
    /// </summary>
    public class SecurityHttpModule : IHttpModule
    {
        public SecurityHttpModule()
        { }

        public void Init( HttpApplication application )
        {
            application.AuthenticateRequest += new EventHandler( this.AuthenticateRequest );
        }

        public void Dispose()
        { }

        /// <summary>
        /// Authenticate Request
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AuthenticateRequest( object sender , EventArgs e )
        {
            HttpApplication app = (HttpApplication)sender;
            HttpContext context = (HttpContext)app.Context;

            //get cookies name
            HttpCookie cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
            if ( null == cookie )
            {
                return;
            }

            //Create a Forms Authentication Ticket.
            FormsAuthenticationTicket authTicket = null;

            try
            {
                authTicket = FormsAuthentication.Decrypt( cookie.Value );
            }
            catch
            {
                return;
            }

            if ( null == authTicket )
            {
                return;
            }

            //split the user roles
            string[] roles = authTicket.UserData.Split( new char[] { ',' } );

            FormsIdentity id = new FormsIdentity( authTicket );

            GenericPrincipal principal = new GenericPrincipal( id , roles );

            context.User = principal;
        }
    }
}
